package com.itic.mall.system.msg.emailsend.service;

import com.itic.appbase.applications.mail.Mail;
import com.itic.appbase.framework.common.basevo.ReturnVo;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.system.inter.msg.emailsend.persistence.dao.EmailSendDao;
import com.itic.mall.system.inter.msg.emailsend.persistence.model.EmailSend;
import com.itic.mall.system.inter.msg.emailsend.persistence.model.EmailSendExample;
import com.itic.mall.system.inter.project.email.persistence.dao.EmailDao;
import com.itic.mall.system.inter.project.email.persistence.model.Email;
import com.itic.mall.system.inter.users.usersmall.persistence.model.UsersMall;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;


@Service
@Transactional
public class EmailSendService
     extends CrudService<EmailSendDao,EmailSend,EmailSendExample> {
    @Autowired
    private EmailSendDao emailSendDao;
    @Autowired
    private EmailDao emailDao;

    /**
     * 发送邮件给用户
     * @param user
     * @param text
     * @return
     */
    public String send( UsersMall user, String text ){
    	EmailSend emailSend = new EmailSend();
    	ReturnVo returnVo = new ReturnVo();
    	returnVo.setStatus(FAILED);
    	Email setSend = emailDao.getEmailByOrgCode(user.getOrgCode());
    	if( StringHelper.isNotBlank(user.getEmail()) ){
    		returnVo = sendMail(setSend,user.getEmail(),text);
    	}else{
    		returnVo.setReturnMsg("用户未设置邮件信息!");
    		emailSend.setSendMail(setSend.getEmailName());
        	emailSend.setReceiveMail(user.getEmail());
    	}
    	emailSend.setSendText(text);
    	emailSend.setStatus(returnVo.getStatus());
    	emailSend.setReturnMsg(returnVo.getReturnMsg());
    	this.initDefalutFields(emailSend);
    	emailSendDao.insert(emailSend);
    	return emailSend.getStatus();
    }
    
    /**
     * 发送邮件
     */
    public ReturnVo sendMail( Email setSend, String receMail, String sendContent ){
    	ReturnVo returnVo = new ReturnVo();
    	returnVo.setStatus(FAILED);
    	try {
	    	String host = setSend.getEmailServer();
	    	String account = setSend.getEmailName();
	    	String password = setSend.getEmailPwd();
	    	Mail mailObj = new Mail(host, account, password, false);
	    	String[] res = new String[1];
	    	res[0] = receMail;
    	
			mailObj.doSendHtmlEmail("京选友惠", sendContent, res , null, null, null);
			returnVo.setStatus(SUCCESS);
			
		} catch (MessagingException e) {
			returnVo.setReturnMsg(e.getMessage());
		}
    	return returnVo;
    }
}